package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.OrderSetting;
import com.xrit.sunnyday.service.OrderSettingService;
import com.xrit.sunnyday.utils.POIUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Reference
    private OrderSettingService orderSettingService;

    /**
     * 处理excel文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile){
        try {
            //1.读取excel内容
            List<String[]> excelString = POIUtils.readExcel(excelFile);
            //2.
            List<OrderSetting> orderSettingList = new ArrayList<OrderSetting>();
            SimpleDateFormat sdf = new SimpleDateFormat(POIUtils.DATE_FORMAT);

            Date orderDate = null;
            OrderSetting os = null;
            //3.遍历将List<String[]>转化成List<OrderSetting>
            for (String[] dataArr:excelString) {
                //格式化每一行的第1个单元格：String->Data
                orderDate = sdf.parse(dataArr[0]);
                //格式化每一行的第2个单元格：String->int
                int number = Integer.valueOf(dataArr[1]);
                //创建OrderSetting，将转化后的值添加
                os = new OrderSetting(orderDate,number);
                orderSettingList.add(os);
            }
            //调用服务
            orderSettingService.add(orderSettingList);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
    }

    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String month){
        //调用服务层
        List<Map<String,Integer>> data = orderSettingService.getOrderSettingByMonth(month);
        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS,data);
    }

    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        //调用服务层
        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }
}
